import { ref, computed } from 'vue'
import { supabase } from '../../lib/supabase'
import type { Tag, TagCategory, MovieTag } from './types'

export const useTagData = () => {
  // 状态
  const tags = ref<Record<string, Tag[]>>({})
  const categories = ref<TagCategory[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const availableGenres = computed(() => 
    tags.value.genre?.map(tag => tag.display_name) || []
  )

  const availableUniverses = computed(() => 
    tags.value.universe?.map(tag => tag.display_name) || []
  )

  const availableLanguages = computed(() => 
    tags.value.language?.map(tag => tag.display_name) || []
  )

  const availableCountries = computed(() => 
    tags.value.country?.map(tag => tag.display_name) || []
  )

  // 获取所有标签分类
  const fetchCategories = async () => {
    try {
      loading.value = true
      error.value = null

      const { data, error: fetchError } = await supabase
        .from('tag_categories')
        .select('*')
        .eq('is_active', true)
        .order('sort_order')

      if (fetchError) throw fetchError

      categories.value = data || []
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取标签分类失败'
      console.error('获取标签分类失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取指定分类的标签
  const fetchTagsByCategory = async (categoryName: string) => {
    try {
      loading.value = true
      error.value = null

      const { data, error: fetchError } = await supabase
        .rpc('get_tags_by_category', { category_name: categoryName })

      if (fetchError) throw fetchError

      tags.value[categoryName] = data || []
    } catch (err) {
      error.value = err instanceof Error ? err.message : `获取${categoryName}标签失败`
      console.error(`获取${categoryName}标签失败:`, err)
    } finally {
      loading.value = false
    }
  }

  // 获取所有标签
  const fetchAllTags = async () => {
    try {
      loading.value = true
      error.value = null

      // 获取所有分类
      await fetchCategories()

      // 获取每个分类的标签
      const categoryNames = categories.value.map(cat => cat.name)
      await Promise.all(categoryNames.map(name => fetchTagsByCategory(name)))
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取标签失败'
      console.error('获取标签失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取电影的标签
  const fetchMovieTags = async (movieId: number): Promise<MovieTag[]> => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('get_movie_tags', { p_movie_id: movieId })

      if (fetchError) throw fetchError

      return data || []
    } catch (err) {
      console.error('获取电影标签失败:', err)
      return []
    }
  }

  // 为电影添加标签
  const addMovieTag = async (movieId: number, tagId: number) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('add_movie_tag', { 
          p_movie_id: movieId, 
          p_tag_id: tagId 
        })

      if (fetchError) throw fetchError

      return data
    } catch (err) {
      console.error('添加电影标签失败:', err)
      throw err
    }
  }

  // 从电影移除标签
  const removeMovieTag = async (movieId: number, tagId: number) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('remove_movie_tag', { 
          p_movie_id: movieId, 
          p_tag_id: tagId 
        })

      if (fetchError) throw fetchError

      return data
    } catch (err) {
      console.error('移除电影标签失败:', err)
      throw err
    }
  }

  // 根据显示名称获取标签ID
  const getTagIdByDisplayName = (categoryName: string, displayName: string): number | null => {
    const categoryTags = tags.value[categoryName]
    if (!categoryTags) return null
    
    const tag = categoryTags.find(tag => tag.display_name === displayName)
    return tag?.id || null
  }

  // 根据显示名称获取标签对象
  const getTagByDisplayName = (categoryName: string, displayName: string): Tag | null => {
    const categoryTags = tags.value[categoryName]
    if (!categoryTags) return null
    
    return categoryTags.find(tag => tag.display_name === displayName) || null
  }

  // 根据标签ID获取标签对象
  const getTagById = (tagId: number): Tag | null => {
    for (const categoryTags of Object.values(tags.value)) {
      const tag = categoryTags.find(tag => tag.id === tagId)
      if (tag) return tag
    }
    return null
  }

  // 获取标签的显示名称列表（用于兼容现有代码）
  const getTagDisplayNames = (categoryName: string): string[] => {
    return tags.value[categoryName]?.map(tag => tag.display_name) || []
  }

  // 初始化标签系统
  const initializeTags = async () => {
    await fetchAllTags()
  }

  return {
    // 状态
    tags,
    categories,
    loading,
    error,

    // 计算属性（兼容现有代码）
    availableGenres,
    availableUniverses,
    availableLanguages,
    availableCountries,

    // 方法
    fetchCategories,
    fetchTagsByCategory,
    fetchAllTags,
    fetchMovieTags,
    addMovieTag,
    removeMovieTag,
    getTagIdByDisplayName,
    getTagByDisplayName,
    getTagById,
    getTagDisplayNames,
    initializeTags
  }
}
